require 'Common/define'
require 'Logic/Config'
require 'Common/functions'

UIBattleSuccess = {};
HelperFunc.SetUIEnv(UIBattleSuccess)
local this = UIBattleSuccess;

function UIBattleSuccess.InitLocalData()
    -- this.gameObject = nil;
    this.transform = nil;
    this.LuaBehaviour = nil;
    this.idleTimer = nil;
    this.hasInit = false;
    this.drawWrappers = {};
    this.objHeroPos = nil;
    this.objHeroDraw = nil;
    this.objContent = nil;
    this.listItemGrid = nil;
    this.btnConfirm = nil;
    this.btnData = nil;
    this.btnBgClose = nil;

    this.spineBeforeSprine = nil;
    this.spineAfterSprine = nil;

    this.spineBefore = nil;
    this.spineAfter = nil;
    this.spineBeforeTimer = nil;
    this.spineAfterTimer = nil;

    this.tableItems = {};

    this.finishFunction = nil;
    this.resultData = nil;
    this.ctrlReward = nil
    this.starObj = {}
    this.mythType = nil
    this.taskConfig = nil;
    this.trialDamage = nil;
    this.trialLv = nil;
    this.trialLvAdd = nil;
    this.trialNewController = nil;
    this.newRecord = nil;

    this.instanceItemScrollViewList = nil;
    this.rank = nil
    this.score = nil
    this.scoreItem = nil;
    this.rankBattleScore = nil
    this.rankBattleAddScore = nil
    this.coinTip = nil

    this.guildBossRewardNum = nil;
    this.guildBossDamageNum = nil;
    this.guildBossRewardList = nil;
    this.funcList = nil
    this.unLockData = nil

    this.destroyed = false
end

this.InitLocalData()

function UIBattleSuccess.Init(func, result)

    --todo 应该小写 暂时先大写
    finishFunction = func;
    this._result = result;
    resultData = {};
    resultData.items = {};
    resultData.heros = {};
    this.tableHeros = {};
    this.fightType = logicMgr.BattlePlaybackManager.GetFightType();
    if this.fightType == EnumConst.FightTypeConst.DUNGEON then
        local mapConfig = logicMgr.MapManager.GetMapcfgByID(logicMgr.MapManager.getMapId());
        local lastTableData = logicMgr.MapManager.GetMapcfgByID(logicMgr.MapManager.getLastMapcfg());
        if mapConfig ~= nil then
            if mapConfig.f_HideNextBtn == 1 then
                resultData.isHideNextBtn = true;
            end
            if mapConfig.f_StageReward ~= nil and #mapConfig.f_StageReward > 0 then
                local items = decodeJsonStrToTabel(mapConfig.f_StageReward);
                for i = 1, #items do
                    local itemModelId = items[i][1];
                    local type = logicMgr.ItemManager.getItemTabType(itemModelId)
                    local itemInfo;
                    if type == EnumConst.ItemTableEnum.Equip then
                        itemInfo = logicMgr.EquipManager.getEquipConstDatabyModelId(itemModelId);
                    else
                        itemInfo = logicMgr.ItemManager.getItemConstDatabyModelId(itemModelId);
                    end
                    if itemInfo then
                        itemInfo.num = items[i][2];
                        table.insert(resultData.items, itemInfo);
                    else
                        logError("[UIBattleSuccess]can't find item or equip in mapConfig by id:" .. itemModelId)
                    end
                end
            end
            if mapConfig.f_StageRewardHero ~= nil and #mapConfig.f_StageRewardHero > 0 then
                local heros = decodeJsonStrToTabel(mapConfig.f_StageRewardHero);
                for i = 1, #heros do
                    local heroConfig = logicMgr.HeroManager.GetHeroConfigbyModelId(heros[i][1]);
                    table.insert(this.tableHeros, heros[i][1]);
                    --local heroInfo = {
                    --    icon = heroConfig.f_HeroIcon,
                    --    quality = logicMgr.HeroManager.starToQuality(heroConfig.f_HeroInitialStar),
                    --    state = EnumConst.HeroHeadStateEnum.NONE
                    --};
                    --table.insert(resultData.heros, heroInfo);
                    table.insert(resultData.items, logicMgr.ItemManager.getItemConstDatabyModelId(heros[i][1] + 201500));
                end
            end
            if lastTableData ~= nil then
                resultData.output = {};
                local timeUnit = getLanguage("Sys_OutPut")
                table.insert(resultData.output, lastTableData.f_Exp .. timeUnit);
                table.insert(resultData.output, mapConfig.f_Exp .. timeUnit);
                table.insert(resultData.output, lastTableData.f_Coin .. timeUnit);
                table.insert(resultData.output, mapConfig.f_Coin .. timeUnit);
                table.insert(resultData.output, lastTableData.f_HeroExp .. timeUnit);
                table.insert(resultData.output, mapConfig.f_HeroExp .. timeUnit);
            end
        end
    elseif this.fightType == EnumConst.FightTypeConst.StoryBattle then
        resultData.items = logicMgr.StoryHardManager.getChapterReward();
    elseif this.fightType == EnumConst.FightTypeConst.TOWER then
        local curTowerType = logicMgr.TowerManager.getClimbType()   --拿到爬塔类型
        local layerId = logicMgr.TowerManager.returnTowerInfo(curTowerType)["layerId"] - 1;
        local rewardsData = logicMgr.TowerManager.returnReward(curTowerType, layerId);
        for i = 1, #rewardsData do
            table.insert(resultData.items, rewardsData[i]);
        end
    elseif this.fightType == EnumConst.FightTypeConst.ARENA then
        local formation_type = logicMgr.BattlePlaybackManager.GetFormationType()
        local lastData = nil
        local nowData = nil
        if formation_type and formation_type == EnumConst.FormationType.CrossArenaAtk then
            lastData = logicMgr.ArenaManager.getLastCrossBaseInfo()
            nowData = logicMgr.ArenaManager.getCrossBaseInfo()
        elseif formation_type and formation_type == EnumConst.FormationType.ArenaAtk then
            lastData = logicMgr.ArenaManager.getLastBaseInfo()
            nowData = logicMgr.ArenaManager.getBaseInfo()
        end
        resultData.arena = {}
        resultData.arena.lastScore = 0
        resultData.arena.addScore = 0
        if lastData ~= nil and nowData ~= nil and next(nowData) ~= nil and next(lastData) ~= nil then
            resultData.arena.lastScore = lastData.score or 0
            resultData.arena.addScore = nowData.score - lastData.score
            resultData.arena.progress = nowData.winCount
            local rewardCfg = nil
            if formation_type and formation_type == EnumConst.FormationType.CrossArenaAtk then
                rewardCfg = G.dataTable["t_arenaboxrewardcs"]
            elseif formation_type and formation_type == EnumConst.FormationType.ArenaAtk then
                rewardCfg = G.dataTable["t_arenaboxreward"]
            end
            if rewardCfg ~= nil then
                resultData.arena.count = rewardCfg["5"].f_winCount + 1;
                for k, v in pairs(rewardCfg) do
                    if v.f_winCount >= resultData.arena.progress and v.f_winCount < resultData.arena.count then
                        resultData.arena.count = v.f_winCount;
                        resultData.arena.reward = v.f_rewards;
                    end
                end
                if resultData.arena.progress > resultData.arena.count then
                    resultData.arena.progress = resultData.arena.count;
                end
            end
        end
    elseif this.fightType == EnumConst.FightTypeConst.INSTANCE then


    elseif this.fightType == EnumConst.FightTypeConst.TRIAL then

    elseif this.fightType == EnumConst.FightTypeConst.GuildBoss then
        local items = GuildManager.getGuideBossReward();
        for id, num in pairs(items) do
            if num ~= 0 then
                local itemInfo = logicMgr.CostManager.getItemOrEquipDataByIdAndNum(id, num);
                table.insert(resultData.items, itemInfo);
            end
        end
    elseif this.fightType == EnumConst.FightTypeConst.DungeonEventPK then
    elseif this.fightType == EnumConst.FightTypeConst.LongJourneyHell then
        resultData.items = logicMgr.LongJourneyHellManager.getReward();
    else
        if not result.items then
            return
        end
        for k, v in pairs(result.items) do
            local itemModelId = v.itemModelId;
            local itemInfo;
            if logicMgr.ItemManager.IsEquip(itemModelId) then
                itemInfo = logicMgr.EquipManager.getEquipConstDatabyModelId(itemModelId);
            else
                itemInfo = logicMgr.ItemManager.getItemConstDatabyModelId(itemModelId);
            end
            if itemInfo then
                itemInfo.num = v.num
                table.insert(resultData.items, itemInfo);
            else
                logError("[UIBattleSuccess]can't find item or equip in mapConfig by id:" .. itemModelId)
            end
        end

    end

    if taskConfig == nil then
        taskConfig = G.dataTable["t_task"];
    end
    local name, packageName = getUIName(PanelNames.UIBattleSuccess);
    panelMgr:ShowUI(name, packageName, this.onCreate, Config.useLocalUI);
end

function UIBattleSuccess.onCreate(obj)
    --战斗胜利界面背景音乐
    AudioManager.Play(7001)
    -- AudioManager.SetSwitch("battle_steps", "end")
    AudioManager.SetSwitch("fight_result", "win")

    --AudioManager.PlaySound(8,obj)

    -- gameObject = obj;
    this.destroyed = false

    if not hasInit then
        hasInit = true;
        objContent = obj:GetChild("itemGrid")
        listItemGrid = obj:GetChild("ItemScrollView")
        btnConfirm = obj:GetChild("ConfirmBtn")
        btnData = obj:GetChild("DataBtn")
        btnBgClose = obj:GetChild("BgClose")

        scoreItem = obj:GetChild("n93")
        objHeroPos = obj:GetChild("HeroPos")
        this.autoClose = obj:GetChild("autoClose")
        spineBefore = obj:GetChild("ui_battle_winb")
        spineAfter = obj:GetChild("ui_battle_winf")
        this.arenaLayer = obj:GetChild("arena")
        this.Com_GuildBattlePlus = obj:GetChild("Com_GuildBattlePlus")
        this.arenaList = obj:GetChild("list")
        this.arenaList.numItems = 0
        this.arena_cross_controller = this.arenaLayer:GetController("ServerIf")
        this.arenaPoint = this.arenaLayer:GetChild("point")
        this.arenaChange = this.arenaLayer:GetChild("pointChange")
        this.arenaItem = this.arenaLayer:GetChild("item")
        this.arenaBar = this.arenaLayer:GetChild("bar")
        this.arenaBarNum = this.arenaBar:GetChild("num")
        this.arenaRewardController = this.arenaLayer:GetController("ifNoRewards")

        this.arenaLayer3 = obj:GetChild("arena3")
        this.arena_title2 = obj:GetChild("title2")
        this.arena_icon = obj:GetChild("icon")

        this.guildBossRewardNum = obj:GetChild("Text_Total");
        this.guildBossDamageNum = obj:GetChild("Text_Hurt");
        this.guildBossRewardList = obj:GetChild("Rewardlist");

        this.battlePage = obj:GetChild("battlePage");
        this.trialDamage = obj:GetChild("pointHurt");
        this.trialLv = obj:GetChild("pointRank");
        this.trialLvAdd = obj:GetChild("pointAdd");
        this.newRecord = obj:GetController("newRecord");
        this.rank = obj:GetChild("rank")
        this.score = obj:GetChild("score")
        this.rankBattleScore = obj:GetChild("Text_RankBattlePointNum")
        this.rankBattleAddScore = obj:GetChild("Text_RankBattlePointChange")
        this.rankBattleItem = obj:GetChild("Btn_RankBattleCoin")
        this.coinTip = obj:GetChild("Text_RankBattleCoinLimit")
        this.trialNewController = obj:GetController("rankup");
        this.mvpController = obj:GetController("Mvp");
        this.shengli = obj:GetChild("shengli").wrapTarget;

        this.txt_rob = obj:GetChild("Text_Rob")
        this.txt_revenge = obj:GetChild("Text_Revenge")
        this.rob_controller = obj:GetController("Rob")
        this.funcList = obj:GetChild("listFunc")

        this.battlePageItems = {};
        for i = 1, 3 do
            table.insert(this.battlePageItems, this.battlePage:GetChild("tipsImprove" .. i));
        end
        this.tableFormationIndex = {};
        for i = 1, 5 do
            local btn = obj:GetChild("team" .. i);
            btn.visible = false;
            table.insert(this.tableFormationIndex, btn);
        end
        ctrlReward = obj:GetController("type")
        this.starObj = {}
        for i=1,3 do
            this.starObj[i] = {}
            this.starObj[i]["ctrl"] = obj:GetController("Star0"..i)
            this.starObj[i]["desc"] = obj:GetChild("text_0"..i)
        end
        this.mythType = obj:GetController("MythicTpye")
        this.clearController = obj:GetController("clear")
        listItemGrid.itemRenderer = this.renderListItem;
        listItemGrid:SetVirtual()
        this.guildBossRewardList.itemRenderer = this.renderListItem;
        this.guildBossRewardList:SetVirtual()
        this.addEvent();
    end
    Util.PlayAction(this.shengli, "start", false);
    if this.shengliTime then
        utimer.remove(this.shengliTime);
    end
    this.shengliTime = utimer.timeCall(function ()
        Util.PlayAction(this.shengli, "idle", true);
        this.shengliTime = nil;
    end, 625);
    this.refresh();
    this.InitUnlockList()

end

function UIBattleSuccess.InitUnlockList()
    local data = logicMgr.TaskManager.getUnlockData()
    this.unLockData = {}
    local mapId = logicMgr.MapManager.getMapId();
    for _,v in ipairs(data) do
        if v.f_UnlockStage > mapId then
            if unLockData[1] and unLockData[1].f_UnlockStage == v.f_UnlockStage  then
                table.insert(unLockData,v)
            end
            if #unLockData == 0 then
                table.insert(unLockData,v)
            end
        end
    end
    funcList.itemRenderer = this.rendererUnLockItem;
    funcList.numItems = #this.unLockData;
end
function UIBattleSuccess.rendererUnLockItem(idx, obj)
    local data = this.unLockData[idx+1]
    local title = obj:GetChild("title")
    local desc = obj:GetChild("desc")
    local unlock = obj:GetChild("unlock")
    title.text = getLanguage("StageFunctionInfoText"..data.f_FunctionId)
    --desc.text = getLanguage("StageFunctionText"..data.f_FunctionId)
    local stageData=G.dataTable["t_stage"][tostring(data.f_UnlockStage) ]
    unlock.text = string.format(getLanguage("UnlockTips1"),stageData.f_ChapterId .. "-" .. stageData.f_StageNum)..getLanguage("StageFunctionText"..data.f_FunctionId)
end

function UIBattleSuccess.addEvent()
    btnConfirm.onClick:Add(this.onClickConfirm);
    btnData.onClick:Add(this.onClickData);
    btnBgClose.onClick:Add(this.onClickBGClose);

end

function UIBattleSuccess.removeEvent()
    btnConfirm.onClick:Clear()
    btnData.onClick:Clear()
    btnBgClose.onClick:Clear()
end

function UIBattleSuccess.LocalListenEvent()

end

function UIBattleSuccess.LocalCloseEvent()
    if spineBeforeTimer ~= nil then
        spineBeforeTimer:Stop();
    end
    if spineAfterTimer ~= nil then
        spineAfterTimer:Stop();
    end
end

function UIBattleSuccess.OnDestroy()
    this.destroyed = true
    if spineBeforeSprine then
        destroy(spineBeforeSprine)
        spineBeforeSprine = nil
    end
    if spineAfterSprine then
        destroy(spineAfterSprine)
        spineAfterSprine = nil
    end

    for key, value in pairs(drawWrappers) do
        if not HelperFunc.IsNull(value) then
            value:Dispose()
        end
    end

    drawWrappers = {}

    if objHeroDraw then
        local name = objHeroDraw.name
        destroyImmediate(objHeroDraw)

        utimer.delayCall(function()
            HelperFunc.UnloadSingleLihui(name)
        end, 1 )

        objHeroDraw = nil
    end

    hasInit = false
    this.removeEvent();
    if idleTimer ~= nil then
        idleTimer:Stop();
    end
    idleTimer = nil

    this.InitLocalData()
end

function UIBattleSuccess.OnEnable()
    this.LocalListenEvent();
end

function UIBattleSuccess.OnDisable()
    this.LocalCloseEvent();
    logicMgr.BattlePlaybackManager.ClearReceiveResult()
end

function UIBattleSuccess.refresh()
    this.isAgain = nil;
    this.isShowSkipTips = false; -- 是否显示跳关
    local dataBtnState = not (FightManager.isRePlay == true);
    local mapCfg = MapManager.GetMapcfgByID(MapManager.getLastMapcfg())
    if not string.IsNilOrEmpty(mapCfg.f_ReportAddress) then
        dataBtnState = false;
    end
    local record = logicMgr.BattlePlaybackManager.getBattleRecord()
    if not record or record.noFight == 1 then
        dataBtnState = false
    end
    btnData.visible = dataBtnState
    if idleTimer ~= nil then
        idleTimer:Stop();
    end

    local heroID, heroType = FightManager.GetMVPHeroId()
    this.mvpController.selectedIndex = heroType;
    local CurHeroConfig = logicMgr.HeroManager.GetHeroConfigbyModelId(heroID);
    local useSkinId = logicMgr.SkinManager.getHeroSkinId(heroID)
    local imageName = logicMgr.HeroManager.GetHeroDrawingPath(heroID,nil,useSkinId)
    if imageName == "" or imageName == nil then
        imageName = "Model/Drawing/drawing_hero_8";
        logError("找不到MVP英雄 id:" .. tostring(heroID));
        heroID = 8;
        dump(CurHeroConfig, "找不到MVP英雄 数据:");
    end

    resMgr:LoadModelPrefab(imageName, function(go)
        if not UIBattleSuccess or UIBattleSuccess.destroyed then
            resMgr.DestroyPrefab(imageName)
            return
        end
        local drawWrapper = drawWrappers["objHeroDraw"];
        if (drawWrapper == nil) then
            drawWrapper = GoWrapper.New();
            drawWrappers["objHeroDraw"] = drawWrapper;
        end
        if objHeroDraw ~= nil then
            destroy(objHeroDraw);
            objHeroDraw = nil;
        end
        objHeroDraw = newObject(go);
        objHeroDraw.name = imageName;--"objHeroDraw";
        objHeroDraw:AddComponent(TCanvas);
        drawWrapper:SetWrapTarget(objHeroDraw, false)
        local scale, location = logicMgr.HeroManager.GetHeroLocationResizeBySkinId(useSkinId)
        Util.Lua_SetLocalPositionXYZ(objHeroDraw.transform, location[1], location[2], 0)
        Util.Lua_SetLocalScaleXYZ(objHeroDraw.transform, scale[1], scale[2], 1)
        if this.objHeroPos then
            this.objHeroPos:SetNativeObject(drawWrapper);
        else
            logError("UIBattleSuccess objHeroPos is NULL")
        end
        --anim
        this.delayIdle();
    end);
    --胜利
    local _index = Mathf.Random(18, 19)
    local _partnerModelId = CurHeroConfig.f_HeroID
    local _skinId = 0
    local _interactionTag = AudioManager.InteractionTagTable[_index].Tag
    AudioManager.PlayInteractionVoice(_partnerModelId, _skinId, _interactionTag)
    UIBattleSuccess.PlayBgmWithFightType(this.fightType)
    this.clearController.selectedIndex = 0;

    if this.fightType == EnumConst.FightTypeConst.DUNGEON then
        ctrlReward.selectedIndex = 1
        local nowStage = logicMgr.MapManager.getMapId();
        local mapConfig = logicMgr.MapManager.GetMapcfgByID(nowStage);
        if not logicMgr.BattlePlaybackManager.GetGroupBossIsOver() and logicMgr.MapManager.getStageNeedTeamNum() > 1 then
            this.clearController.selectedIndex = 1;
            for i = 1, logicMgr.MapManager.getStageNeedTeamNum() do
                local go = this.tableFormationIndex[i];
                go.visible = true;
                go:GetController("Clear").selectedIndex = 0;
                local data = logicMgr.BattlePlaybackManager.GetGroupBossHistory(i);
                if data and data.record and data.record.win == 1 then
                    go:GetController("Clear").selectedIndex = 1;
                end
            end
        elseif logicMgr.MapManager.GetIsCanSkip() then
            if mapConfig ~= nil and not logicMgr.MapManager.IsEndChapterMapId(nowStage) then
                if mapConfig.f_SkipStageTarget > nowStage and not logicMgr.GuideMgr.HasGuidingInRankLevel(nowStage, mapConfig.f_SkipStageTarget) and not logicMgr.StoryMgr.HasStoryInRankLevel(nowStage, mapConfig.f_SkipStageTarget) then
                    this.isShowSkipTips = true;
                    this.skipStageName = "";
                    this.nowStageName = "";
                    local skipTableData = logicMgr.MapManager.GetMapcfgByID(mapConfig.f_SkipStageTarget);
                    if skipTableData ~= nil then
                        this.nowStageName = string.format("%d-%d", mapConfig.f_ChapterId, mapConfig.f_StageNum);
                        this.skipStageName = string.format("%d-%d", skipTableData.f_ChapterId, skipTableData.f_StageNum);
                    end
                end
            end
        end
        if resultData.isHideNextBtn or logicMgr.StoryMgr.HasStoryInRankLevel(nowStage, mapConfig.f_NextStage) then
            btnConfirm.visible = false;
        else
            btnConfirm.visible = true;
        end
        if resultData.output ~= nil and #resultData.output >= 3 then
            for i = 1, 3 do
                local ctrl = this.battlePageItems[i]:GetTransition("Effect_List")
                local lastNum = this.battlePageItems[i]:GetChild("numBefore");
                local nowNum = this.battlePageItems[i]:GetChild("numAfter");
                lastNum.text = resultData.output[i * 2 - 1];
                nowNum.text = resultData.output[i * 2];
                this.battlePageItems[i].alpha = 0
                ctrl:Play(1,0.12*(i),function()
                    this.battlePageItems[i].alpha = 1
                end)
            end
        end
    elseif this.fightType == EnumConst.FightTypeConst.ARENA then
        ctrlReward:SetSelectedIndex( 2 )
        if resultData.arena.reward then
            this.arenaRewardController:SetSelectedIndex(0)
            this.arenaBarNum.text = resultData.arena.progress .. "/" .. resultData.arena.count;
            this.arenaBar.value = resultData.arena.progress * 100 / resultData.arena.count;
            logicMgr.CostManager.RefreshItem(this.arenaItem, resultData.arena.reward[1]);
        else
            this.arenaRewardController:SetSelectedIndex(1)
        end
        this.arenaPoint.text = resultData.arena.lastScore;
        this.arenaChange.text = "+" .. resultData.arena.addScore;
        local formation_type = logicMgr.BattlePlaybackManager.GetFormationType()
        if formation_type and formation_type == EnumConst.FormationType.CrossArenaAtk then
            this.arenaRewardController:SetSelectedIndex(0)
            local img_level = this.arenaLayer:GetChild("Effect_Dwsg")
            local txt_level = this.arenaLayer:GetChild("text2")
            local level_color_controller = this.arenaLayer:GetController("rank")
            local info = logicMgr.ArenaManager.getCrossBaseInfo()
            local level_cfg, newLevel = logicMgr.ArenaManager.getLevelConfigByScore(info.score, EnumConst.ArenaBattleType.Cross)
            img_level.animationName = "idle" .. newLevel
            img_level.skinName = newLevel
            img_level.loop = true
            txt_level.text = level_cfg and getLanguage(level_cfg.f_Name) or "--"
            level_color_controller:SetSelectedIndex(newLevel-1)
            this.arena_cross_controller:SetSelectedIndex(1)
        elseif formation_type and formation_type == EnumConst.FormationType.TeamCrossArenaAtk then
            this.ctrlReward:SetSelectedIndex( 11 )
            local icon_my = this.arenaLayer3:GetChild("IconMy")
            local txt_my_level = this.arenaLayer3:GetChild("levelMy")
            local icon_enemy = this.arenaLayer3:GetChild("IconEnemy")
            local txt_enemy_level = this.arenaLayer3:GetChild("levelEnemy")
            local txt_num = this.arenaLayer3:GetChild("num")
            local my_img_level = this.arenaLayer3:GetChild("MyEffect_Dwsg")
            local enemy_img_level = this.arenaLayer3:GetChild("EnemyEffect_Dwsg")
            local win_count = FightManager.cross_team_battle_data and FightManager.cross_team_battle_data["win_count"] or 0
            txt_num.text = string.format("%s:%s", win_count, 3-win_count)
            this.arenaList.itemRenderer = this.ArenaItemRender
            this.arenaList.numItems = 3
            local attacker_score = FightManager.cross_team_battle_data and FightManager.cross_team_battle_data["attacker_score"]
            local cfg_grading, cfg_arena_matching_item = ArenaManager.getAthleticGradingConfigByRank( attacker_score )
            local teamBaseInfo = logicMgr.ArenaManager.getCrossTeamBaseInfo()
            if teamBaseInfo ~= nil then
                local gradingCfg, cfg_item = logicMgr.ArenaManager.getAthleticGradingConfigByRank(teamBaseInfo.rank)
                this.arena_title2.text = string.format("%s/小时", cfg_item.f_Coin)
            else
                this.arena_title2.text = string.format("%s/小时", cfg_arena_matching_item.f_Coin)
            end
            --this.arena_title2.text = string.format("%s/小时", cfg_arena_matching_item.f_Coin)
            this.arena_icon.url = EnumConst.AtlasPath.ItemAtlas..logicMgr.ItemManager.GetItemIcon(31)
            icon_my.url = EnumConst.AtlasPath.ICONAtlas .. cfg_grading.f_Icon
            txt_my_level.text = getLanguage(cfg_arena_matching_item.f_RankName)
            local my_level = cfg_grading.f_RankId
            my_img_level.animationName = "idle" .. my_level
            my_img_level.skinName = my_level
            my_img_level.loop = true

            local defener_score = FightManager.cross_team_battle_data and FightManager.cross_team_battle_data["defener_score"]
            local cfg_grading1, cfg_matching1 = ArenaManager.getAthleticGradingConfigByRank(defener_score)
            icon_enemy.url = EnumConst.AtlasPath.ICONAtlas .. cfg_grading1.f_Icon
            txt_enemy_level.text = getLanguage(cfg_matching1.f_RankName)
            local enemy_level = cfg_grading1.f_RankId
            enemy_img_level.animationName = "idle" .. enemy_level
            enemy_img_level.skinName = enemy_level
            enemy_img_level.loop = true
        else
            this.arena_cross_controller:SetSelectedIndex(0)
        end
    elseif this.fightType == EnumConst.FightTypeConst.TOWER then
        ctrlReward:SetSelectedIndex( 4 )
        if logicMgr.TowerManager.getIsCanSkip() then
            this.towerType = logicMgr.TowerManager.getClimbType();
            local layerData = logicMgr.TowerManager.returnTowerInfo(this.towerType);
            local layerId = layerData.layerId - 1;
            local skipLayerId = logicMgr.TowerManager.getTowerJumpLayer(this.towerType, layerId);
            local layerLimit = logicMgr.TowerManager.getAdvancedTowerToDayLimit(this.towerType);
            this.skipLayer = math.min(skipLayerId, layerId + layerLimit - layerData.todayLayer + 1);
            if this.skipLayer > layerId + 1 then
                this.isShowSkipTips = true;
            end
        end
    elseif this.fightType == EnumConst.FightTypeConst.INSTANCE then
        ctrlReward:SetSelectedIndex( 5 )
        local starInfo = logicMgr.MythicDungeonsProManager.GetResultStar()
        local cfg = dataTable.getDataTableByStringId("t_mythicdungeons",MythicDungeonsProManager.getLayer())
        for i=1,3 do
            this.starObj[i].ctrl.selectedIndex = 0
            local condition_1 = cfg["f_MythicStarParameter0"..i][1]
            local condition_2 = cfg["f_MythicStarParameter0"..i][2] or 0
            if cfg["f_MythicStarTpye0"..i]== 4 then
                condition_2 = getLanguage("HeroType"..condition_2)
            end
            if cfg["f_MythicStarTpye0"..i]== 9 then
                condition_1 = getLanguage("MythicHeroType0"..condition_1)
            end
            if cfg["f_MythicStarTpye0"..i]== 7 then
                condition_1 = getLanguage("HeroName"..condition_1)
            end
            if cfg["f_MythicStarTpye0"..i]== 2 then
                condition_1 = condition_1/1000
            end
            this.starObj[i].desc.text = string.format(getLanguage(cfg["f_MythicStarLanguage0"..i]),condition_1,condition_2)
        end
        if #starInfo > 0 then
            for _,v in ipairs(starInfo) do
                this.starObj[v].ctrl.selectedIndex = 1
            end
        end
        --[[local time = MythicDungeonsManager.getBattleTime();
        local cfg = decodeJsonStrToTabel(G.dataTable["t_global"]["83"].f_string_value);
        local lv = 0;
        for i = 1, #cfg do
            if time < cfg[i][2] then
                lv = cfg[i][1];
                break ;
            end
        end
        logicMgr.MythicDungeonsManager.SetLayerLevel(lv)
        scoreItem:GetController("rank"):SetSelectedIndex(lv - 1)--]]
        resultData.items = MythicDungeonsProManager.getItemInfos();
        if #resultData.items > 0 then
            this.mythType.selectedIndex = 1
        else
            this.mythType.selectedIndex = 0
        end
    elseif this.fightType == EnumConst.FightTypeConst.Expedition or this.fightType == EnumConst.FightTypeConst.LongJourneyHell then
        ctrlReward:SetSelectedIndex( 6 )
    elseif this.fightType == EnumConst.FightTypeConst.TRIAL then
        ctrlReward:SetSelectedIndex( 3 )
        local info = logicMgr.TrialsManager.GetBattleInfo();
        local rankInfo = logicMgr.TrialsManager.GetMyRankInfo();
        this.trialDamage.text =getNumString(info.score) ;
        if info.rank > 0 then
            this.trialLv.text = info.rank;
        else
            this.trialLv.text = getLanguage("NotInRank")
        end
        if rankInfo.workRank <= 0 then
            this.trialLvAdd.visible = false;
        else
            this.trialLvAdd.visible = true;
        end
        local addLv = (info.rank - rankInfo.workRank);
        if addLv > 0 and rankInfo.workRank > 0 then
            trialNewController:SetSelectedIndex( 0 )
            this.trialLvAdd.text = addLv;
        else
            trialNewController:SetSelectedIndex( 1 )
        end
        local rankInfoId = info.rank;

        local cfg_trialsrank = G.dataTable["t_trialsrank"]
        local num = 0
        for _, _ in pairs(cfg_trialsrank) do
            num = num+1
        end
        if rankInfoId == nil or rankInfoId <= 0 or rankInfoId > num then
            rankInfoId = num
        end
        local rewardConfig = decodeJsonStrToTabel(G.dataTable["t_trialsrank"][tostring(rankInfoId)].f_Reward);
        for i = 1, #rewardConfig do
            local itemInfo = logicMgr.ItemManager.getItemConstDatabyModelId(rewardConfig[i][1]);
            local power = logicMgr.EcoBuffManager.getEcoBuffByTypeAndItemId(Config.EcoBuffCondition.ChaosTestReward, rewardConfig[i][1]);
            itemInfo.num = Mathf.Round(rewardConfig[i][2] * (1 + power * 0.0001));
            table.insert(resultData.items, itemInfo);
        end

        local battleScore = tonumber(info.score or 0)
        local rankScore   = tonumber(rankInfo.score or 0)
        this.newRecord:SetSelectedIndex( battleScore > rankScore and 1 or 0 )
        if FightManager.resultExtraItems ~= nil and next(FightManager.resultExtraItems) ~= nil then
            showUI(PanelNames.UICommonItemGet, nil, nil, 3, FightManager.resultExtraItems)
            FightManager.InitExtraRewards(nil)
        end
    elseif this.fightType == EnumConst.FightTypeConst.FriendAttack then
        ctrlReward:SetSelectedIndex( 7 )
        local result = logicMgr.FriendBattleManager.GetFightResult()
        local myInfo = logicMgr.FriendBattleManager.GetFriendChallengeList()
        local rank = tonumber(tostring(result.rank)) or 0
        local lastRank = tonumber(tostring(myInfo.rank)) or 0
        local score = tonumber(tostring(result.score)) or 0
        local lastScore = tonumber(tostring(myInfo.score)) or 0
        local rankNum = (lastRank - rank) < 0 and 0 or (lastRank - rank)
        local rstr = ""
        if rankNum ~= 0 then
            rstr = "(" .. "+" .. rankNum .. ")"
        end
        this.rank.text = rank .. rstr
        local str = ""
        if score - lastScore ~= 0 then
            str = "(" .. "+" .. (score - lastScore) .. ")"
        end
        this.score.text = score .. str
    elseif this.fightType == EnumConst.FightTypeConst.RankBattle then
        ctrlReward:SetSelectedIndex( 8 )
        local config = logicMgr.RankBattleManager.GetResult()
        local info = logicMgr.RankBattleManager.GetMyInfo()
        local scoreNum = tonumber(tostring(info.score))
        if scoreNum == 0 then
            scoreNum = 1200
        end
        this.rankBattleScore.text = tostring(scoreNum - math.abs(tonumber(tostring(config.score))))
        this.rankBattleAddScore.text = "+" .. tostring(config.score)
        logicMgr.CostManager.RefreshItem(this.rankBattleItem, { CurrencyEnum.GOLD, config.coin });
        local hasNum = tonumber(tostring(info.weekCoin))
        local maxNum = G.dataTable["t_global"]["208"].f_int_value
        this.coinTip.text = string.format(getLanguage("RankBattleResultTips"), hasNum, maxNum)
    elseif this.fightType == EnumConst.FightTypeConst.Plunder then
        ctrlReward:SetSelectedIndex( 10 )
        if plunderHandler.is_rob then
            this.txt_rob.text = string.format(getLanguage("RogueSuccess"), plunderHandler.atk_target_name)
            this.rob_controller:SetSelectedIndex(0)
        else
            if plunderHandler.is_help then
                this.txt_revenge.text = ""
                this.rob_controller:SetSelectedIndex(1)
            else
                this.txt_revenge.text = string.format(getLanguage("RevengeSuccess"), plunderHandler.atk_target_name)
                this.rob_controller:SetSelectedIndex(1)
            end
        end
        if FightManager.resultExtraItems ~= nil and next(FightManager.resultExtraItems) ~= nil then
            showUI(PanelNames.UICommonItemGet, nil, nil, 3, FightManager.resultExtraItems)
            FightManager.InitExtraRewards(nil)
        end

    elseif this.fightType == EnumConst.FightTypeConst.GuildBoss then
        ctrlReward:SetSelectedIndex( 9 )
        this.guildBossRewardNum.text = GuildManager.getCount();
        this.guildBossDamageNum.text = string.format(getLanguage("GuildInvestment_1131"), GuildManager.getGuideBossDamage());

        guildBossRewardList.itemProvider = this.getListItem;
        guildBossRewardList.numItems = #resultData.items;
    elseif this.fightType == EnumConst.FightTypeConst.GuildBattlePlus then
        this.ctrlReward:SetSelectedIndex(12)
        local txt_num = this.Com_GuildBattlePlus:GetChild("num")
        this.guideBattleList = logicMgr.GuildBattlePlusManager.getAttackInfo();
        txt_num.text = string.format("%s:%s", logicMgr.GuildBattlePlusManager.getAttackScore())
        this.arenaList.itemRenderer = this.GuildBattlePlusItemRender
        this.arenaList.numItems = #this.guideBattleList
    elseif this.fightType == EnumConst.FightTypeConst.SoloChaosTest then
        if logicMgr.SoloChaosTestManager.getNowBossId() == logicMgr.SoloChaosTestManager.getEndLessBossId() then
            this.ctrlReward:SetSelectedIndex(14)
        else
            this.ctrlReward:SetSelectedIndex(13)
        end
        this.trialDamage.text = getNumString(logicMgr.SoloChaosTestManager.getOpenUI("harm"))
        if logicMgr.SoloChaosTestManager.getOpenUI("newRecord") then
            this.newRecord.selectedIndex = 1;
        else
            this.newRecord.selectedIndex = 0;
        end
        if logicMgr.SoloChaosTestManager.getOpenUI("rank") and logicMgr.SoloChaosTestManager.getOpenUI("rank") > 0 then
            this.trialLvAdd.text = "+"..logicMgr.SoloChaosTestManager.getOpenUI("rank")
            this.trialNewController.selectedIndex = 0;
            this.trialLvAdd.visible = true;
        else
            this.trialNewController.selectedIndex = 1;
        end
        this.trialLv.text = (logicMgr.SoloChaosTestManager.getOpenUI("nowRank") or 0);

    elseif this.fightType == EnumConst.FightTypeConst.StoryBattle then
        this.ctrlReward:SetSelectedIndex(15)   --剧情模式胜利界面  待处理
        if not logicMgr.BattlePlaybackManager.GetGroupBossIsOver() then
            this.clearController.selectedIndex = 1;
            for i = 1, logicMgr.MapManager.getStoryBattleNeedTeamNum() do
                local go = this.tableFormationIndex[i];
                go.visible = true;
                go:GetController("Clear").selectedIndex = 0;
                local data = logicMgr.BattlePlaybackManager.GetGroupBossHistory(i);
                if data and data.record and data.record.win == 1 then
                    go:GetController("Clear").selectedIndex = 1;
                end
            end
        else
            this.clearController.selectedIndex = 0;
        end
        this.autoClose.visible = false;
        btnData.visible = true;
        local _countDown = 3;
        --if FightManager.AutoGoFight(EnumConst.FightTypeConst.StoryBattle) then
        --    btnData.visible = false;
        --    this.autoClose.visible = true;
        --    this.autoClose.text = string.format("%s秒后自动推关", _countDown);
        --    this.autoUTimer = utimer.timeCall(function ()
        --        _countDown = _countDown - 1;
        --        if _countDown <= 0 then
        --            this.autoUTimer = nil;
        --            logicMgr.StoryHardManager.autoBattle();
        --        else
        --            this.autoClose.text = string.format("%s秒后自动推关", _countDown);
        --        end
        --    end, 1000, _countDown);
        --else
            this.autoUTimer = utimer.timeCall(function ()
                _countDown = _countDown - 1;
                if _countDown <= 0 then
                    this.autoUTimer = nil;
                    this.onClickClose();
                end
            end, 1000, _countDown);
        --end
    else
        ctrlReward:SetSelectedIndex( 0 )
    end
    if this.fightType ~= EnumConst.FightTypeConst.GuildBoss then
        listItemGrid.itemProvider = this.getListItem;
        listItemGrid.numItems = #resultData.items + #resultData.heros;
    end
    if resultData.taskInfos ~= nil and #resultData.taskInfos > 0 then
        objContent.itemRenderer = this.renderListTask;
        objContent.numItems = #resultData.taskInfos;
    end

    Util.AddAction(spineBeforeSprine, "win_start", false, 0.5);
    if spineBeforeTimer == nil then
        spineBeforeTimer = Timer.New(this.switchBeforeAni, 1.2, 1, false);
    else
        spineBeforeTimer:Reset(this.switchBeforeAni, 1.2, 1, false);
    end
    spineBeforeTimer:Start();

    Util.AddAction(spineAfterSprine, "win_start", false, 0.5);
    if spineAfterTimer == nil then
        spineAfterTimer = Timer.New(this.switchAfterAni, 1.1, 1, false);
    else
        spineAfterTimer:Reset(this.switchAfterAni, 1.1, 1, false);
    end
    spineAfterTimer:Start();
    if this.isShowSkipTips and (not FighterInfo.isAuto) then
        if this.fightType == EnumConst.FightTypeConst.DUNGEON then
            local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop);
            pop.Init("63", function(b)
                if b then
                    dungeonHandler.sendReqSkipDungeon()
                    this.onClickClose();
                end
            end, this.skipStageName);
        elseif this.fightType == EnumConst.FightTypeConst.TOWER then
            local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop);
            pop.Init("74", function(b)
                if b then
                    logicMgr.TowerManager.addLayer(this.towerType, this.skipLayer)
                    towerHandler.sendTowerJump(this.towerType)
                    this.onClickClose();
                end
            end, this.skipLayer);
        end
    end
end

function UIBattleSuccess.ArenaItemRender(index, obj)
    this.UpdateItemRender(index, obj, FightManager.cross_team_battle_data[index+1]);
end
function UIBattleSuccess.GuildBattlePlusItemRender(index, obj)
    this.UpdateItemRender(index, obj,  this.guideBattleList[index+1]);
end
function UIBattleSuccess.UpdateItemRender(index, obj, data)
    if data ~= nil then
        local ctrl_win = obj:GetController("ifWin")
        local txt_my_name = obj:GetChild("nameMy")
        local txt_enemy_name = obj:GetChild("nameEnemy")
        local head_my = obj:GetChild("headMy")
        local head_enemy = obj:GetChild("headEnemy")
        local my_hero_list = obj:GetChild("heroMy")
        local enemy_hero_list = obj:GetChild("heroEnemy")
        local txt_num = obj:GetChild("num")
        local btn_play = obj:GetChild("n5")
        btn_play.onClick:Clear()

        local num_str = "第一场"
        if index == 1 then
            num_str = "第二场"
        elseif index == 2 then
            num_str = "第三场"
        end
        txt_num.text= num_str
        if data.win == 1 then
            ctrl_win:SetSelectedIndex(0)
        else
            ctrl_win:SetSelectedIndex(1)
        end
        btn_play.onClick:Add(function()
            BattlePlaybackManager.ClearMultiFightData()
            BattlePlaybackManager.AddMultiFightData( data.fightId, data.win, logicMgr.BattlePlaybackManager.GetFightType(), data, nil, -1, -1)
            BattlePlaybackManager.GotoNextFight(true)
        end)

        local attacker = data.attacker
        local defender = data.defender
        txt_my_name.text = attacker.playerName or "--"
        txt_enemy_name.text = defender.playerName or "--"

        head_my:GetChild("head"):GetChild("HeadIcon").url = logicMgr.SkinManager.GetHeroIconBySkinId(attacker.pic)
        -- EnumConst.AtlasPath.ICONAtlas .. dataTable.getRow("t_hero", attacker.pic)["f_HeroIcon"]
        head_my:GetChild("frame").url = EnumConst.AtlasPath.ICONAtlas .. attacker.picFrame

        head_enemy:GetChild("head"):GetChild("HeadIcon").url = logicMgr.SkinManager.GetHeroIconBySkinId(defender.pic)
        -- EnumConst.AtlasPath.ICONAtlas .. dataTable.getRow("t_hero", defender.pic)["f_HeroIcon"]
        head_enemy:GetChild("frame").url = EnumConst.AtlasPath.ICONAtlas .. defender.picFrame

        my_hero_list.itemRenderer = this.renderHeroItem
        enemy_hero_list.itemRenderer = this.renderHeroItem2
        this.my_hero_list_data = attacker.members or {}
        my_hero_list.numItems = #this.my_hero_list_data
        this.enemy_hero_list_data = defender.members or {}
        enemy_hero_list.numItems = #this.enemy_hero_list_data
    end
end

function UIBattleSuccess.renderHeroItem(index, obj)
    local data = this.my_hero_list_data[index+1]
    this.showItemInfo( obj, data )
end
function UIBattleSuccess.renderHeroItem2(index, obj)
    local data = this.enemy_hero_list_data[index+1]
    this.showItemInfo( obj, data )
end
function UIBattleSuccess.showItemInfo( obj, item_info )
    local quality = obj:GetChild("quality")
    local qualityBG = obj:GetChild("qualityBG")
    local icon = obj:GetChild("icon")
    local lv = obj:GetChild("level")
    local lvbg = obj:GetChild("n29")
    local choose = obj:GetChild("maskChoose")
    local unActive = obj:GetChild("unActive")
    local circleCtrl = obj:GetController("Circle")
    local comIcon = obj:GetChild("Com_icon")
    local levelShowCtrl = obj:GetController("isShowLevel")--0显示等级以及底框 1不显示
    quality.visible = false
    qualityBG.visible = false
    choose.visible = false
    unActive.visible = false
    icon.visible = false
    if item_info then
        if item_info.star ~= nil then
            item_info.quality = logicMgr.HeroManager.starToQuality(item_info["star"]);
        end
        local hero_item = G.dataTable["t_hero"][tostring(item_info.partnerModelId)]
        if levelShowCtrl ~= nil then
            if item_info.level ~= nil and item_info.level > 0 then
                levelShowCtrl:SetSelectedIndex(0)
                lv.visible = true
                lvbg.visible = true
                local level, lvType = logicMgr.HeroManager.getHeroShowLevelByPartnerId(item_info.partnerId)
                lv.text = string.TextColor(string.format(getLanguage("Level"), level),logicMgr.HeroManager.lvColors[lvType])
            else
                levelShowCtrl:SetSelectedIndex( 1 )
            end
        end
        if hero_item ~= nil then
            if circleCtrl and circleCtrl.selectedIndex == 1 then
                comIcon.visible = true
                comIcon:GetChild("icon").url = "ui://ICONAtlas/" .. hero_item.f_HeroIcon
            else
                icon.visible = true
                icon:GetChild("icon").url = "ui://ICONAtlas/" .. hero_item.f_HeroIcon
            end
            icon.visible = true
            icon:GetChild("icon").url = "ui://ICONAtlas/" .. hero_item.f_HeroIcon
            if item_info.quality == nil or item_info.quality == 0 then
                item_info.quality = 1
            elseif item_info.quality > #Config.IconQuality then
                item_info.quality = #Config.IconQuality
            end
            quality.visible = true
            qualityBG.visible = true
            quality.url = "ui://ICONAtlas/" .. Config.IconFrame[item_info.quality]
            qualityBG.url = "ui://ICONAtlas/" .. Config.IconQuality[item_info.quality]
        end
    end
end

function UIBattleSuccess.PlayBgmWithFightType(type)

    local config = G.dataTable["t_Global"]["320"]
    local pvp = false
    for _, v in pairs(config.f_string_value) do
        if type == v then
            pvp = true
            break
        end
    end
    if pvp then
        AudioManager.Play(302)
        --logError(302)
    else
        AudioManager.Play(301)
        --logError(301)
    end
    AudioManager.SetSwitch("battle_steps", "end")
end

function UIBattleSuccess.delayIdle()
    if objHeroDraw ~= nil then
        objHeroDraw:GetComponent("SkeletonGraphic").AnimationState:SetAnimation(0, "idle1", true);
    end
    idleTimer = nil
end
function UIBattleSuccess.getListItem(index)
    if (index + 1 <= #resultData.items) then
        return "ui://CommonUI/Item"
    else
        return "ui://CommonUI/HeadRectItem"
    end

end

function UIBattleSuccess.renderListItem(index, obj)
    local data = {}
    if (index + 1 <= #resultData.items) then
        data = resultData.items[index + 1];
        local itemCtr = CtrlManager.GetCtrl(PanelNames.Item);
        if itemCtr then
            itemCtr.initData(obj, data);
        end
    else
        data = resultData.heros[index - #resultData.items + 1];
        local itemCtr = CtrlManager.GetCtrl(PanelNames.HeadRectItem);
        itemCtr.initData(obj, data);
        obj.touchable = false;
    end
end

function UIBattleSuccess.renderListTask(index, obj)
    local dataStr = resultData.taskInfos[index];
    local taskId = data.taskId;
    local progress = data.progress;
    local singleConfig = taskConfig[tostring(taskId)];
    local taskName = getLanguage(singleConfig.f_TaskDesc);
    local target = singleConfig.f_Progress;
    if progress > target then
        progress = target;
    end

    local txtName = obj:GetChild("Name");
    local txtProgress = obj:GetChild("Progress");
    local txtProgressMax = obj:GetChild("ProgressMax");
    --local objSignController = obj:GetController();
    local objSign = obj:GetChild("FinishSign");

    txtName.text = taskName;
    txtProgress.text = progress;
    txtProgressMax = target;
    objSign.visible = progress >= target;
end

function UIBattleSuccess.switchBeforeAni()
    Util.AddAction(spineBeforeSprine, "win_fidle", true, 0.5);
end

function UIBattleSuccess.switchAfterAni()
    Util.AddAction(spineAfterSprine, "win_fidle", true, 0.5);
end

function UIBattleSuccess.onClickConfirm()
    TAManager.TrackByDictionary("ui_battle_success_click_continue")
    local nowStage = logicMgr.MapManager.getMapId();
    if not logicMgr.StoryMgr.HasStoryInRankLevel(nowStage, nowStage + 1) then
        this.isAgain = true;
    end
    if this.fightType == EnumConst.FightTypeConst.TOWER then
        logicMgr.TowerManager.ShowUIBattleTeam()
    end
    this.onClickClose();
end

function UIBattleSuccess.onClickData()
    local formation_type = logicMgr.BattlePlaybackManager.GetFormationType()
    if (this.fightType == EnumConst.FightTypeConst.DUNGEON and logicMgr.BattlePlaybackManager.GetGroupBossIsOver() and logicMgr.MapManager.getStageNeedTeamNum(logicMgr.MapManager.getMapId()) > 1)
            or this.fightType == EnumConst.FightTypeConst.SoloChaosTest then
        showUI(PanelNames.UITeamsRecode, this.fightType, logicMgr.BattlePlaybackManager.GetGroupBossHistory(), nil, function ()
            showUI(PanelNames.UIBattleSuccess, finishFunction, this._result);
        end , nil, formation_type);
    else
        showUI(PanelNames.UILevelRecode, this.fightType, logicMgr.BattlePlaybackManager.getBattleRecord(), nil, function ()
            showUI(PanelNames.UIBattleSuccess, finishFunction, this._result);
        end, nil, formation_type);
    end
    TAManager.TrackByDictionary("ui_battle_success_click_data")
end

function UIBattleSuccess.onClickBGClose()
    TAManager.TrackByDictionary("ui_battle_success_click_close")
    this.onClickClose()
    if logicMgr.BattlePlaybackManager.GetFightType() == EnumConst.FightTypeConst.FriendAttack then
        -- FriendBattleHandler.ReqFriendBattleInfo()
        --FriendBattleHandler.ReqGoodFriendList()
    end
end

function UIBattleSuccess.onClickClose()
    partnerHandler.tryReqPartnerInteract()
    plunderHandler.is_rob = nil
    if this.shengliTime then
        utimer.remove(this.shengliTime);
        this.shengliTime = nil;
    end
    if this.autoUTimer then
        utimer.remove(this.autoUTimer);
        this.autoUTimer = nil;
    end
    Util.SetPlayerPrefs("StagePlay", 1);
    DestoryBattleInUI(1);
    if finishFunction ~= nil then
        finishFunction();
    end
    if this.fightType == EnumConst.FightTypeConst.DUNGEON then
        if logicMgr.BattlePlaybackManager.GetGroupBossIsOver() then
            logicMgr.BattlePlaybackManager.SetGroupBossHistory();
            logicMgr.MapManager.SetIsCanSkip();
            local mapConfig = logicMgr.MapManager.GetMapcfgByID(logicMgr.MapManager.getMapId());
            if this.fightType == EnumConst.FightTypeConst.DUNGEON and not logicMgr.StoryMgr.ShowStoryByStageId(mapConfig.f_StageId, function()
                if FightManager.isRePlay ~= true then
                    this.showNewHerosByIndex(0);
                end
            end) then
                if FightManager.isRePlay ~= true then
                    this.showNewHerosByIndex(0);
                end
            end
        else
            log("onClickClose BossIsOver "..tostring(logicMgr.BattlePlaybackManager.GetGroupBossIsOver()))
            UIBattle.onClickBoss();
        end
    end
    if this.fightType == EnumConst.FightTypeConst.StoryBattle then
        if logicMgr.BattlePlaybackManager.GetGroupBossIsOver() then
            logicMgr.BattlePlaybackManager.SetGroupBossHistory();
            UIBattle.onAutoHardMode(false)
            if this.fightType == EnumConst.FightTypeConst.StoryBattle and not logicMgr.StoryMgr.ShowStoryByStageId(dungeonHandler.hardData.maxPassDungeon, function()
                --if FightManager.isRePlay ~= true then
                --    this.showNewHerosByIndex(0);
                --end
            end, true) then

            end
        else
            UIBattle.onAutoHardMode(true)
        end
    end
    if this.fightType == EnumConst.FightTypeConst.TOWER then
        this.showFlashGiftPopUp();
    elseif this.fightType == EnumConst.FightTypeConst.Plunder then
        if plunderHandler.rob_item_data ~= nil then
            plunderHandler.UpdateRobListData()
        end
        plunderHandler.sendReqPlunderInfo()
        --showUI(PanelNames.UIBigMap, true)
        if plunderHandler.is_help then
            plunderHandler.is_help = nil
            showUI(PanelNames.UIGuild)
            showUI(PanelNames.UIGuildRescue)
        end
    end
end

--1、新英雄
function UIBattleSuccess.showNewHerosByIndex(index)
    FireEvent(Config.EventType.WaitingBattleFinishedPopUp,true)
    index = index + 1;
    if index <= #this.tableHeros then
        local heroTableData = logicMgr.HeroManager.getHeroDatabyModelId(this.tableHeros[index], true);
        if heroTableData ~= nil and heroTableData.isNew then
            logicMgr.HeroManager.setHeroIsNew(heroTableData.partnerId, false, TAManager.GetHeroSource.MainStage)
            showUI(PanelNames.UIDrawAnimation, this.tableHeros[index], nil, false, function()
                this.showNewHerosByIndex(index)
            end, nil, true);
        else
            this.showNewHerosByIndex(index);
        end
    else
        closeUI(PanelNames.UIDrawAnimation);
        this.tableHeros = {};
        if this.fightType == EnumConst.FightTypeConst.DUNGEON and not this.isAgain then
            showUI(PanelNames.UICommonOutput);
        end
        this.showLevelUpPopUp();
    end
end

--2、升级
function UIBattleSuccess.showLevelUpPopUp()
    if logicMgr.HeroManager.GetLastPlayerLevel() < logicMgr.HeroManager.GetRoleLevel() then
        showUI(PanelNames.UICommonLevelUp, logicMgr.HeroManager.GetLastPlayerLevel(), logicMgr.HeroManager.GetRoleLevel(), function()
            this.showNewChapterPopUp()
        end);
        logicMgr.HeroManager.SetLastPlayerLevel(logicMgr.HeroManager.GetRoleLevel());
        logicMgr.UnlockFuncManager.updateUnlockFunc(); -- 解锁功能，发起协议
    else
        this.showNewChapterPopUp();
    end
end

--3、新章节
function UIBattleSuccess.showNewChapterPopUp()
    if this.fightType == EnumConst.FightTypeConst.DUNGEON and logicMgr.MapManager.isOpenNewChapter() then
        showUI(PanelNames.UICommonNewChapter, function()
            this.showSevenDay()
        end);
    else
        this.showSevenDay();
    end
end

--4、新手七天
function UIBattleSuccess.showSevenDay()

    FireEvent(Config.EventType.StageRotate)
    logicMgr.GuideMgr.Resume()
    logicMgr.GuideMgr.CheckGuide(true)
    FireEvent(Config.EventType.WaitingBattleFinishedPopUp,false)
    --有引导不弹
    local stageId = logicMgr.MapManager.getMapId()
    if logicMgr.GuideMgr.HasGuidingInStage(stageId) then
        return
    end
    if this.fightType == EnumConst.FightTypeConst.DUNGEON and stageId == HelperFunc.GetGlobalNumVlue(190) and logicMgr.ActiveManager.isHaveSevenDay() then
        logicMgr.HeroManager.showLocalityUIByName("BattleShowSevenDayUI_", PanelNames.UISevenday, this.showDungeonRandomEvent);
    else
        this.showDungeonRandomEvent();
    end
end

--5、限时
function UIBattleSuccess.showFlashGiftPopUp()
    if not logicMgr.FlashGiftManager.showNewFlashGift() and this.isAgain  then
        if this.fightType == EnumConst.FightTypeConst.TOWER then
            --logicMgr.TowerManager.ShowUIBattleTeam()
        else
            UIBattle.onClickBoss2();
        end

    end
end

--6、主线随机事件  ps：顺序在限时前面
function UIBattleSuccess.showDungeonRandomEvent()
    if this.fightType == EnumConst.FightTypeConst.DUNGEON and not this.isAgain and logicMgr.DungeonRandomEventManager.getEventState() then
        logicMgr.DungeonRandomEventManager.OpenDungeonRandomEventUI(this.showFlashGiftPopUp);
    else
        logicMgr.DungeonRandomEventManager.setEventState(false);
        this.showFlashGiftPopUp();
    end
end

return UIBattleSuccess;
